package lzzy17;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Date;

public class Server extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        TextArea textArea = new TextArea();
        Scene scene = new Scene(new ScrollPane(textArea),450,200);
        primaryStage.setTitle("Server");
        primaryStage.setScene(scene);
        primaryStage.show();
        new Thread(() -> {
            try {
                ServerSocket serverSocket = new ServerSocket(8000);
                Platform.runLater(() ->
                        textArea.appendText("Server started at "+ new Date()+ "\n")
                );
                Socket socket = serverSocket.accept();
                DataInputStream inputStream = new DataInputStream(socket.getInputStream());
                DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
                while (true){
                    double h = inputStream.readDouble();
                    double w = inputStream.readDouble();
                    double bmi = w/(h*h);
                    String result;
                    if (31.9 <bmi){
                        result = "非常肥胖";
                    }else if(27.9<bmi){
                        result = "肥胖";
                    }else if (23.9 < bmi){
                        result = "体重过重";
                    }else if (18.5< bmi){
                        result = "正常";
                    }else {
                        result = "体重过轻";
                    }
                    outputStream.writeDouble(bmi);
                    outputStream.writeUTF(result);
                    Platform.runLater(() -> {
                        textArea.appendText("身高："+h+"  " + "体重："+w+"\n");
                        textArea.appendText("BMI为: "+bmi+"  属于："+result+"\n");
                    });

                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

    }
    public static void main(String[] args) {
        launch(args);
    }
}